package com.demo.accessibilitykeeper;

import android.accessibilityservice.AccessibilityService;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * 屏幕遮罩Activity
 * 功能：在屏幕上显示纯黑色遮罩，阻止所有触摸操作
 */
public class MaskActivity extends Activity {
    private static final String TAG = "MaskActivity";
    
    private View maskView;
    private Handler uiHandler;
    private Runnable hideSystemUIRunnable;
    
    // 无障碍服务实例，用于创建顶层悬浮框
    private static AccessibilityService accessibilityService = null;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "MaskActivity created");
        
        // 设置全屏透明主题
        setupFullscreenTheme();
        
        // 创建遮罩视图
        setupMaskView();
        
        // 设置系统UI可见性
        hideSystemUI();
        
        // 设置窗口属性
        setupWindowParams();
    }
    
    /**
     * 设置全屏透明主题
     */
    private void setupFullscreenTheme() {
        // 移除标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        // 设置全屏标志 - 隐藏状态栏和导航栏
        getWindow().setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN |
            WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
            WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
            WindowManager.LayoutParams.FLAG_FULLSCREEN |
            WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
            WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
        );
        
        // 设置透明背景（隐藏状态栏和导航栏）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            getWindow().setNavigationBarColor(Color.TRANSPARENT);
            
            // 确保状态栏和导航栏透明
            getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            );
        }
        
        // 设置窗口背景透明
        getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        
        Log.d(TAG, "✅ Fullscreen theme setup completed");
    }
    
    /**
     * 创建遮罩视图
     */
    private void setupMaskView() {
        // 创建纯黑色遮罩视图
        maskView = new View(this);
        maskView.setBackgroundColor(0xFF000000); // 纯黑色
        maskView.setClickable(true);
        maskView.setFocusable(true);
        
        // 拦截所有触摸事件
        maskView.setOnTouchListener((v, event) -> {
            Log.d(TAG, "🎭 MASK_TOUCH_INTERCEPTED - Blocking all touch events");
            return true; // 消费所有触摸事件
        });
        
        // 设置为内容视图
        setContentView(maskView);
    }
    
    /**
     * 隐藏系统UI（状态栏和导航栏）
     */
    private void hideSystemUI() {
        View decorView = getWindow().getDecorView();
        
        // 使用最强的隐藏标志组合
        int systemUiVisibility = View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LOW_PROFILE;
        
        decorView.setSystemUiVisibility(systemUiVisibility);
        
        // 监听系统UI可见性变化，确保系统UI保持隐藏
        decorView.setOnSystemUiVisibilityChangeListener(visibility -> {
            // 如果状态栏或导航栏显示了，立即重新隐藏
            if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0 ||
                (visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) {
                Log.d(TAG, "⚠️ System UI appeared, hiding again...");
                // 延迟一点再隐藏，确保系统UI变化完成
                if (uiHandler != null) {
                    uiHandler.postDelayed(() -> hideSystemUI(), 100);
                } else {
                    hideSystemUI();
                }
            }
        });
        
        // 启动定期检查，确保系统UI始终保持隐藏
        startSystemUICheck();
        
        Log.d(TAG, "✅ System UI hidden (status bar and navigation bar)");
    }
    
    /**
     * 启动系统UI检查（定期检查并重新隐藏）
     */
    private void startSystemUICheck() {
        if (uiHandler == null) {
            uiHandler = new Handler(Looper.getMainLooper());
        }
        
        // 移除之前的检查任务
        if (hideSystemUIRunnable != null) {
            uiHandler.removeCallbacks(hideSystemUIRunnable);
        }
        
        // 创建定期检查任务
        hideSystemUIRunnable = () -> {
            View decorView = getWindow().getDecorView();
            int currentVisibility = decorView.getSystemUiVisibility();
            
            // 检查系统UI标志
            boolean isFullscreen = (currentVisibility & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0;
            boolean isHideNavigation = (currentVisibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) != 0;
            
            if (!isFullscreen || !isHideNavigation) {
                Log.d(TAG, "⚠️ System UI check: not fully hidden, re-hiding...");
                hideSystemUI();
            }
            
            // 每500ms检查一次
            if (uiHandler != null && hideSystemUIRunnable != null) {
                uiHandler.postDelayed(hideSystemUIRunnable, 500);
            }
        };
        
        // 启动定期检查
        uiHandler.postDelayed(hideSystemUIRunnable, 500);
    }
    
    /**
     * 停止系统UI检查
     */
    private void stopSystemUICheck() {
        if (uiHandler != null && hideSystemUIRunnable != null) {
            uiHandler.removeCallbacks(hideSystemUIRunnable);
            hideSystemUIRunnable = null;
        }
    }
    
    /**
     * 显示系统UI
     */
    private void showSystemUI() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        );
        Log.d(TAG, "✅ System UI shown");
    }
    
    /**
     * 设置窗口参数
     */
    private void setupWindowParams() {
        WindowManager.LayoutParams params = getWindow().getAttributes();
        
        // 设置窗口大小 - 覆盖整个屏幕包括状态栏和导航栏
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
        
        // 设置窗口位置
        params.gravity = Gravity.TOP | Gravity.LEFT;
        params.x = 0;
        params.y = 0;
        
        // 设置窗口标志 - 强制全屏，隐藏状态栏和导航栏
        params.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN
                     | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                     | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
                     | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
                     | WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS
                     | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
        
        // 应用窗口参数
        getWindow().setAttributes(params);
        
        Log.d(TAG, "✅ Window params setup completed with fullscreen flags");
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "MaskActivity resumed");
        
        // 确保系统UI保持隐藏
        hideSystemUI();
        
        // 检查是否需要自动启动持续遮罩
        checkAndStartPersistentMask();
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "MaskActivity paused");
        
        // 即使在暂停时也保持系统UI隐藏
        hideSystemUI();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        
        // 停止系统UI检查
        stopSystemUICheck();
        
        // 清理Handler
        if (uiHandler != null) {
            uiHandler.removeCallbacksAndMessages(null);
            uiHandler = null;
        }
        
        Log.d(TAG, "MaskActivity destroyed");
    }
    
    @Override
    public void onBackPressed() {
        // 拦截返回键，不允许关闭遮罩（除非是特定的关闭指令）
        String action = getIntent() != null ? getIntent().getStringExtra("action") : null;
        if ("close".equals(action)) {
            finish();
        } else {
            Log.d(TAG, "🚫 Back button intercepted - mask stays active");
            // 可以选择显示提示或什么都不做
            // 不调用 super.onBackPressed()，这样返回键就不会关闭Activity
        }
    }
    
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            // 当窗口获得焦点时，确保系统UI保持隐藏
            hideSystemUI();
        }
    }
    
    /**
     * 检查并启动持续遮罩
     */
    private void checkAndStartPersistentMask() {
        try {
            SharedPreferences prefs = getSharedPreferences("persistent_mask_prefs", MODE_PRIVATE);
            boolean isPersistentMaskEnabled = prefs.getBoolean("persistent_mask_enabled", false);
            
            if (!isPersistentMaskEnabled) {
                // 如果持续遮罩未启用，可以选择保持Activity运行
                Log.d(TAG, "Persistent mask not enabled");
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CHECKING_PERSISTENT_MASK_STATUS", e);
        }
    }
    
    /**
     * 设置无障碍服务实例（由无障碍服务调用）
     */
    public static void setAccessibilityService(AccessibilityService service) {
        accessibilityService = service;
        Log.d(TAG, "✅ AccessibilityService set: " + (service != null ? "available" : "null"));
    }
    
    /**
     * 检查无障碍服务是否启用
     */
    private boolean isAccessibilityServiceEnabled() {
        try {
            String settingValue = Settings.Secure.getString(
                getContentResolver(),
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            
            String packageName = getPackageName();
            String serviceName = packageName + "/" + packageName + ".AccessibilityKeeperService";
            
            boolean isEnabled = settingValue != null && settingValue.contains(serviceName);
            Log.d(TAG, "Accessibility service enabled: " + isEnabled);
            return isEnabled;
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CHECKING_ACCESSIBILITY_SERVICE", e);
            return false;
        }
    }
    
    /**
     * 启动遮罩Activity
     */
    public static void startMask(Context context) {
        Intent intent = new Intent(context, MaskActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
        Log.d(TAG, "✅ MaskActivity started");
    }
    
    /**
     * 关闭遮罩Activity
     */
    public static void closeMask(Context context) {
        Intent intent = new Intent(context, MaskActivity.class);
        intent.putExtra("action", "close");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
        Log.d(TAG, "✅ Closing MaskActivity");
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        
        // 检查是否有关闭指令
        String action = intent.getStringExtra("action");
        if ("close".equals(action)) {
            Log.d(TAG, "✅ Received close action, finishing activity");
            finish();
        }
    }
}

